package chances.wechat.msggw.context;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

//import chances.wechat.msggw.impl.GwConfig;
import chances.wechat.utils.EncodeUtils;

public class BaseContext {
	protected static final String EMPTY_STR = "";
	protected String url = EMPTY_STR;
	protected String body = EMPTY_STR;
	protected String cmd = EMPTY_STR;
	protected long timestamp;

	static Logger logger = LoggerFactory.getLogger("baseContext");

	public BaseContext() {
		this.timestamp = System.currentTimeMillis();
	}

	public String getCmd() {
		return cmd;
	}

	public void setCmd(String cmd) {
		this.cmd = cmd;
	}

	public String getUrl() {
		return url;
	}

	public String getBody() {
		return body;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public void setBody(String body) {
		this.body = body;
	}

	public long getTimestamp() {
		return timestamp;
	}

	public void setTimestamp(long timestamp) {
		this.timestamp = timestamp;
	}

//	public static String signUrl(GwConfig config, String bindUrl) {
//		String url = bindUrl;
//		String qs = "";
//		int fix = bindUrl.indexOf("?");
//		if (fix != -1) {
//			url = url.substring(0, fix);
//			qs = bindUrl.substring(fix + 1);
//		}
//		Map<String, String> params = queryStringToMap(qs);
//
//		logger.debug("sig params {}.", params);
//
//		String sig = sig(params, config.getKey());
//		logger.debug("sig is {}.", sig);
//
//		String gotoUrl = toUrl(url, params) + "sig=" + sig;
//		logger.debug("gotoUrl is {}.", gotoUrl);
//
//		return gotoUrl;
//	}

	public static Map<String, String> queryStringToMap(String queryString) {
		String[] paramValues = queryString.split("&");
		String[] keyValues;
		Map<String, String> params = new LinkedHashMap<String, String>();
		for (String paramValue : paramValues) {
			keyValues = paramValue.split("=");
			if (keyValues.length < 2) {
				params.put(keyValues[0], "");
			} else {
				params.put(keyValues[0], keyValues[1]);
			}
		}
		return params;
	}

	public static String toUrl(String url, Map<String, String> params) {
		StringBuffer sb = new StringBuffer(url + "?");
		for (Entry<String, String> paramValue : params.entrySet()) {
			sb.append(paramValue.getKey()).append("=").append(paramValue.getValue()).append("&");
		}
		return sb.toString();
	}

	public static String sig(Map<String, String> map, String key) {
		List<String> keys = new ArrayList<String>(map.keySet());
		Collections.sort(keys);
		StringBuilder sb = new StringBuilder(key);
		for (String k : keys) {
			if ("sig".equals(k))
				continue;
			sb.append("#").append(map.get(k).trim());
		}
		logger.debug("md5 str is{}.", sb.toString());
		return EncodeUtils.md5(sb.toString());
	}
}
